<?php
class ModelExtensionOauthAlipayUser extends Model
{
    public $table = 'alipay_user';

    public function bindCustomer($customer_id, $user_id)
    {
        $tbl = $this->getTable();
        $sql = "UPDATE $tbl SET customer_id = '$customer_id' WHERE alipay_user_id = '$user_id' ";

        $query = $this->db->query($sql);

	    return $query->num_rows;
	}

    public function find($key)
    {
        $tbl = $this->getTable();
        $sql = "SELECT * FROM $tbl WHERE alipay_user_id = '$key' ";

        $query = $this->db->query($sql);

        return $query->row;
	}

    public function findByUserId($user_id)
    {
        $tbl = $this->getTable();
        $sql = "SELECT * FROM $tbl WHERE user_id = '$user_id' ";

        $query = $this->db->query($sql);

        return $query->row;
	}

    /**
     * @param array $user_info
     *
     * @return array
     * @throws Exception
     */
    public function updateOrCreateUserInfo($user_info)
    {
        $tbl = $this->getTable();

        $user_id = $user_info['user_id'];
        $find = $this->findByUserId($user_id);

        $user_data_sql = $this->assembleSetSql($user_info);
        $updated_at = '`updated_at` = NOW()';
        if ($find) {
            $sql = "UPDATE $tbl SET $user_data_sql, $updated_at WHERE `user_id` = $user_id";
            $query = $this->db->query($sql);
        } else {
            $sql = "INSERT INTO $tbl SET $user_data_sql, $updated_at";
            $query = $this->db->query($sql);

            $find = $this->findByUserId($user_id);
        }

        if (! $query->num_rows) {
            throw new \Exception('sql error');
        }

        return $user_info + $find;
    }
}
